package org.misalen.web.server.util;

import org.misalen.web.database.util.PaginationFrom;
import org.misalen.web.server.result.Empty;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

/**
 * depend on jackson
 * 
 * @author Diamond
 */
public class CustomerJsonSerializer {

	static final String DYNC_INCLUDE = "DYNC_INCLUDE";
	static final String DYNC_FILTER = "DYNC_FILTER";
	ObjectMapper mapper = new ObjectMapper();

	@JsonFilter(DYNC_FILTER)
	interface DynamicFilter {
	}

	@JsonFilter(DYNC_INCLUDE)
	interface DynamicInclude {
	}

	/**
	 * @param clazz
	 *            需要设置规则的Class
	 * @param include
	 *            转换时包含哪些字段
	 * @param filter
	 *            转换时过滤哪些字段
	 */
	public void filter(Class<?>[] clazz, String[] include, String[] filter) {
		if (clazz.length == 0)
			return;
		for (Class<?> class1 : clazz) {
			if (class1 != Empty.class && class1 != PaginationFrom.class) {
				if (include != null && include.length > 0) {
					mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_INCLUDE,
							SimpleBeanPropertyFilter.filterOutAllExcept(include)));
					mapper.addMixIn(class1, DynamicInclude.class);
				} else if (filter != null && filter.length > 0) {
					mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_FILTER,
							SimpleBeanPropertyFilter.serializeAllExcept(filter)));
					mapper.addMixIn(class1, DynamicFilter.class);
				}
				return;
			}
		}
	}

	public String toJson(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
}